const ssim = require('ssim.js')
const path = require('path')
const fs = require('fs')
const glob = require('glob')
const Canvas = require('canvas')

const getLimitDimensions = (width, height, limit) => {
  if (limit && width >= limit && height >= limit) {
    const ratio = width / height

    if (ratio > 1) {
      return { height: limit, width: Math.round(limit / ratio) }
    }
    return { height: Math.round(limit * ratio), width: limit }
  }
  return { width, height }
}

const loadImgData = (path) => {
  let data = fs.readFileSync(path)
  let imgData = Canvas.loadImage(data).then((img) => {
    //let { width, height } = getLimitDimensions(img.width, img.height, 300)
    let width = 300
    let height = 300
    const canvas = Canvas.createCanvas(width, height)
    const ctx = canvas.getContext('2d')

    ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height)

    return ctx.getImageData(0, 0, width, height)
  })
  return imgData
}

const compareImg = (path1, path2) => {
  return loadImgData(path1)
    .then((f1) => {
      return loadImgData(path2).then((f2) => [f1, f2])
    })
    .then(([f1, f2]) => {
      try {
        let res = ssim.ssim(f1, f2)
        return res
      } catch (ex) {
        console.log(ex)
      }
    })
}

compareImg('./pics/p3_small.png', './pics/p3_big.png').then((res) => {
  console.log(res)
})
